package com.tansun.easycare.rule.datamodel.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.rule.common.DataCache;
import com.tansun.easycare.rule.common.ReferenceModel;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.model.RuleSetParamInfo;
import com.tansun.easycare.rule.common.service.RuleSetParmOperator;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.datamodel.dao.RuleDatamodelDao;
import com.tansun.easycare.rule.datamodel.dao.RuleDataparamsDao;
import com.tansun.easycare.rule.datamodel.dao.RuleDatasetDao;
import com.tansun.easycare.rule.datamodel.entity.RuleDatamodel;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.entity.RuleDataset;
import com.tansun.easycare.rule.datamodel.model.DataSourceVo;
import com.tansun.easycare.rule.datamodel.service.DataModelService;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.excel.entity.ruledataset.RuleDataParamsExcelEntity;
import com.tansun.easycare.rule.excel.entity.ruledataset.RuleDatasetExcelEntity;
import com.tansun.easycare.rule.excel.service.RuleDatasetExcelService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.referencedata.dao.RuleReferenceDataDao;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.rulemange.dao.RuleManageDao;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleproj.entity.RuleProjectRank;
import com.tansun.easycare.rule.ruleproj.service.RuleProjectRankService;
import com.tansun.rule.common.RuleModelTypeEnum;

/**
 * 数据模型逻辑层对象，用于管理数据集的增删改查等操作的页面请求
 *
 * @author WY
 */
@Service("dataModelService")
public class DataModelServiceImpl extends RuleBaseServiceImpl<RuleDatasetDao, RuleDataset> implements DataModelService {

    @Autowired
    private RuleDataparamsDao ruleDataparamsDao;

    @Autowired
    private RuleDatasetDao RuleDatasetDao;
    
    @Autowired
    private RuleDatamodelDao RuleDatamodelDao;
    
    @Autowired
	private RuleManageDao ruleManageDao;

	@Autowired
	private RuleReferenceDataDao ruleReferenceDataDao;

    @Autowired
    private RuleDatasetExcelService ruleDatasetExcelService;

    @Autowired
    private RuleReferenceDataService ruleReferenceDataService;
    @Autowired
	private RuleManageService ruleManageService;
    @Autowired
	private RuleProjectRankService ruleProjectRankService;
    
    @Autowired
    private  RuleSetParmOperator  ruleSetParmOperator;

	@Override
	public void saveOrUpdateDataset(RuleDataset ruleDataset) {
        this.save(ruleDataset);
   }

	@Override
    public PageInfo<RuleDataset> findRuleDatasetPage(Page<RuleDataset> page, RuleDataset ruleDataset) {
        ruleDataset.setPage(page);
        ruleProjectRankService.setRefRandIds(ruleDataset,false);
        PageInfo<RuleDataset> pageInfo = new PageInfo<>(this.dao.queryRuleDataList(ruleDataset));
        return pageInfo;
    }
    
    @Override
	public PageInfo<RuleDatamodel> findRuleDatamodelPage(Page<RuleDatamodel> page, RuleDatamodel ruleDatamodel) {
		ruleProjectRankService.setRefRandIds(ruleDatamodel,false);
		List<RuleDatamodel> list = this.RuleDatamodelDao.findRuleDatamodelList(ruleDatamodel);
        PageInfo<RuleDatamodel> pageInfo = new PageInfo<>(list);
        return pageInfo;
	}

	@Override
	public PageInfo<ReferenceModel> findReferenceData(Map<String, Object> map) {
		String datasetId = (String)map.get("datasetId");
		RuleDataset ruleDataset = this.dao.get(datasetId);
		RuleReferenceData ruleReferenceData = new RuleReferenceData();
		ruleReferenceData.setProjectCode((String)map.get("projectCode"));
		ruleReferenceData.setNameen((String)map.get("nameen"));
		ruleReferenceData.setClassName(ruleDataset.getName());
		ruleReferenceData.setPageNum(Integer.parseInt((map.get("pageNum").toString())));
		ruleReferenceData.setPageSize(Integer.parseInt((map.get("pageSize").toString())));
		PageInfo<RuleReferenceData> pageInfo=new PageInfo<>(this.ruleReferenceDataDao.findReferenceDataList(ruleReferenceData));
		List<ReferenceModel> refList = new ArrayList();
		ReferenceModel referenceModel = null;
		for (RuleReferenceData referenceData : pageInfo.getList()) {
			referenceModel = new ReferenceModel();
			try {
				BeanUtils.copyProperties(referenceModel, ruleReferenceData);
			}catch(IllegalAccessException e) {
				e.printStackTrace();
				
			}catch(InvocationTargetException e) {
				e.printStackTrace();
				
			}
			referenceModel.setFlowName(referenceData.getRefName());
			referenceModel.setReferenceName(RuleModelTypeEnum.getName(referenceData.getModelType()));
			referenceModel.setReferenceVer(referenceData.getVersion());
			refList.add(referenceModel);
		}
		PageInfo<ReferenceModel> pageInfo2 = new PageInfo<>();
		try {
			BeanUtils.copyProperties(pageInfo2, pageInfo);
			pageInfo2.setList(refList);
		} catch(IllegalAccessException e) {
			e.printStackTrace();
			
		}catch(InvocationTargetException e) {
			e.printStackTrace();
			
		}
		return pageInfo2;
	}

	/**
     * 新建数据模型
     * @param dm
     */
    @Override
	public void saveDatamodel(RuleDatamodel dm) {
    	dm.preInsert();
		this.RuleDatamodelDao.insert(dm);
	}
	@Override
	public void updateDatamodel(RuleDatamodel dm) {
		this.RuleDatamodelDao.update(dm);
	}

	@Override
    public List<RuleDataset> getDataModelListByProjectCode(String projectCode, String modelCode) throws BizException {
        RuleDataset ruleDataset = new RuleDataset();
        ruleDataset.setProjectcode(projectCode);
        // ruleDataset.setCode(modelCode);
        return this.dao.queryRuleDataList(ruleDataset);

    }

	@Override
	public PageInfo<RuleDataset> findDatasetForMove(RuleDataset ruleDataset) {
    	PageInfo<RuleDataset> pageInfo = new PageInfo<>(this.dao.queryRuleDataList(ruleDataset));
		return pageInfo;
	}

	@Override
    public void deleteDataModelById(String id) throws BizException {
    	/*判断是否被引用*/
    	RuleDataset rds = this.get(id);
    	RuleReferenceData condition=new RuleReferenceData(); //实例化rule_reference_data
    	condition.setProjectCode(rds.getProjectcode());//获取rule_dataset 的ProjectCode
    	condition.setClassName(rds.getName());  //获取rule_dataset的name
    	List<RuleReferenceData> refList = ruleReferenceDataService.findReferenceParamList(condition);
    	if(refList!=null && refList.size()>0){
    		throw new BizException("数据集被引用，不能删除！");
    	}else{    	
    		RuleDataset ruleDataset = new RuleDataset();
            ruleDataset.setId(id);
            this.dao.deleteflag(ruleDataset);
            RuleDataparams   ruleDataParam = new  RuleDataparams();
            ruleDataParam.setDatasetId(id);
            this.ruleDataparamsDao.deleteflag(ruleDataParam);
    	}
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("id", id);
//        this.dao.deleteDataModelById(map);
//        Map<String, String> tmpMap = new HashMap<String, String>();
//        tmpMap.put("datasetId", id);
//        this.ruleDataparamsDao.deleteBydatasetId(tmpMap);
    }
    @Override
    public void deleteDataModelPlusById(String id) throws BizException {
    	/*判断是否被引用*/
//    	RuleDataset rds = this.get(id);
//    	RuleReferenceData condition=new RuleReferenceData(); //实例化rule_reference_data
//    	condition.setProjectCode(rds.getProjectcode());//获取rule_dataset 的ProjectCode
//    	condition.setClassName(rds.getName());  //获取rule_dataset的name
//    	List<RuleReferenceData> refList = ruleReferenceDataService.findReferenceParamList(condition);
//    	if(refList!=null && refList.size()>0){
//    		throw new BizException("E-200003");
//    	}else{
            RuleDataset  queryDataset  = new  RuleDataset();
            queryDataset.setDatamodelid(id);
            List<RuleDataset> list =  this.RuleDatasetDao.queryRuleDataList(queryDataset);
            for (RuleDataset  rDataset :list) {
            	this.deleteDataModelById(rDataset.getId());
            }
    		RuleDatamodel ruleDatamodel = new RuleDatamodel();
    		ruleDatamodel.setId(id);
            RuleDatamodelDao.deleteflag(ruleDatamodel);
//    	}
    }

    @Override
    public List<RuleDataset> getList(RuleDataset dataset) {
        return this.dao.getList(dataset);
    }

    @Override
    public PageInfo<RuleDataset> findListPageByInfo(Page<RuleDataset> page, RuleDataset ruleDataset) {
        ruleDataset.setPage(page);
        PageInfo<RuleDataset> pageInfo  = new  PageInfo<>();
        pageInfo.setList(this.dao.findListByInfo(ruleDataset));
        return pageInfo;
    }
    @Override
    public PageInfo<RuleDatamodel> findDatamodelListPageByInfo(Page<RuleDatamodel> page, RuleDatamodel ruleDatamodel) {
        ruleDatamodel.setPage(page);
        PageInfo<RuleDatamodel> pageInfo  = new PageInfo<>();
        pageInfo.setList(RuleDatamodelDao.findDatamodelListByInfo(ruleDatamodel));
        return pageInfo;
    }

    @Override
    public void ToEntity(DataSourceVo vo, String projectCode) {
        RuleDatasetExcelEntity dataset = new RuleDatasetExcelEntity();
        List<RuleDatasetExcelEntity> ruleDatasetList = new ArrayList<RuleDatasetExcelEntity>();
        List<RuleDataParamsExcelEntity> ruleDataparamsList = new ArrayList<RuleDataParamsExcelEntity>();

        RuleDataset entity = new RuleDataset();
        entity.setName(vo.getRds().getName());
        entity.setProjectcode(projectCode);
        List<RuleDataset> findList = this.RuleDatasetDao.queryRuleDataList(entity);


        if (findList.size() > 0) {
            for (int i = 0; i < vo.getRdplist().size(); i++) {
                if (vo.getRdplist().get(i).getLength() != null) {
                    RuleDataparams params = new RuleDataparams();
                    params.setName(vo.getRdplist().get(i).getName());
                    params.setProjectcode(projectCode);
                    params.setDatasetId(findList.get(0).getId());
                    List<RuleDataparams> findList2 = this.ruleDataparamsDao.findList(params);
                    if (findList2.size() > 0) {
                        continue;
                    } else {
                        params.setChzn(vo.getRdplist().get(i).getChzn());
                        params.setType(vo.getRdplist().get(i).getType());
                        params.setDefaultValue("0");
                        params.setParamDesc("");
                        params.setIsCollections("false");
                        params.setIsDerives("false");
                        params.setIsout("false");
                        params.preInsert();
                        ruleDataparamsDao.insert(params);
                    }
                }
            }
        } else {
            dataset.setName(vo.getRds().getName());
            dataset.setProjectcode(projectCode);
            dataset.setChzn(vo.getRds().getChzn());
            dataset.setParamType("ALL");
            dataset.preInsert();
            ruleDatasetList.add(dataset);
            for (int i = 0; i < vo.getRdplist().size(); i++) {
                if (vo.getRdplist().get(i).getLength() != null) {
                    RuleDataParamsExcelEntity params = new RuleDataParamsExcelEntity();
                    params.setName(vo.getRdplist().get(i).getName());
                    params.setChzn(vo.getRdplist().get(i).getChzn());
                    params.setType(vo.getRdplist().get(i).getType());
                    params.setDefaultValue("0");
                    params.setParamDesc("");
                    params.setIsCollections("false");
                    params.setIsDerives("false");
                    params.setIsout("false");
                    params.setDatasetId(dataset.getId());
                    params.preInsert();
                    params.setProjectcode(projectCode);
                    ruleDataparamsList.add(params);
                }
            }
            if (ruleDatasetList != null && ruleDatasetList.size() > 0) {
                ruleDatasetList.get(0).setParamsList(ruleDataparamsList);
            }
            ruleDatasetExcelService.saveExcelInfoToDb(ruleDatasetList);
        }
    }

    @Override
    public List<RuleDataset> findListByInfo(RuleDataset ruleDataset) {
        return RuleDatasetDao.findListByInfo(ruleDataset);
    }

    @Override
    public List<RuleDataset> findDatasetList(RuleDataset ruleDataset) {
        return RuleDatasetDao.findDatasetList(ruleDataset);
    }

/*    @Override
    public List<RuleDataset> queryRuleDataList(RuleDataset ruleDataset) {
        // TODO Auto-generated method stub
        return this.findList(ruleDataset);
    }*/
    
    @Override
    public List<RuleDataset> queryRuleDataList(RuleDataset ruleDataset) {
        return RuleDatasetDao.queryRuleDataList(ruleDataset);
    }
    @Override
    public List<RuleDatamodel> queryRuleDatamodelList(RuleDatamodel ruleDatamodel) {
        return RuleDatamodelDao.findRuleDatamodelList(ruleDatamodel);
    }
    
    @Autowired
    private RuleDataparamsService ruleDataparamsService;
    /**
     * 初始化或更新内置变量
     * @param ruleDataset
     * @return
     */
    public void saveOrUpdateBuiltinParam(String code,String name,String type,String projectCode,String user) {
    	DataCache.paramChange(projectCode);
    	RuleDataset condition = new RuleDataset();
    	condition.setProjectcode(projectCode);
    	condition.setName("builtinParam");
    	List<RuleDataset> dsList = this.findList(condition);
    	RuleDataset builtinSet = null;
    	if(dsList.size()==0) {
    		builtinSet = new RuleDataset();
    		builtinSet.setProjectcode(projectCode);
    		builtinSet.setName("builtinParam");
    		builtinSet.setChzn("内置变量");
    		builtinSet.setParamType("ALL");
    		builtinSet.setIsbuiltin("1");
    		builtinSet.setCreateBy(user);
    		this.save(builtinSet); 
    		dsList.add(builtinSet);
    	}
    	
    	if(RuleModelTypeEnum.PolicyRuleGroup.code.equals(type)) {
    		RuleDataset grouopSet = new RuleDataset();
			grouopSet.setProjectcode(projectCode);
			grouopSet.setName(code);
			grouopSet.setParamType("ALL");
			grouopSet.setIsbuiltin("1");
			List<RuleDataset> dstList = this.findList(grouopSet);
			if( dstList.size()==0 ) {
				grouopSet.setChzn(name);
				grouopSet.setCreateBy(user);
				this.save(grouopSet);
			}else {
				RuleDataset dst1 = dstList.get(0);
	    		if( !name.equals(dstList.get(0).getChzn()) ) {
	    			dst1.setChzn(name);
	    			this.save(dst1);
	    		}
			}
			
    		List<RuleDataparams> pList = new ArrayList<RuleDataparams>();
    		
    		if(!isExistParam(projectCode,grouopSet.getId(),"reasonList")) {
        		RuleDataparams p0 = new RuleDataparams();
        		p0.setDatasetId(grouopSet.getId());
        		p0.setProjectcode(projectCode);
        		p0.setChzn("原因代码");
        		p0.setName("reasonList");
        		p0.setCollection("List");
        		p0.setIsCollections("true");
        		p0.setIsDerives("false");
        		p0.setIsout("false");
        		p0.setType("String");
        		p0.setCreateBy(user);
        		pList.add(p0);
    		}

    		if(!isExistParam(projectCode,grouopSet.getId(),"ruleScoreList")) {
	    		RuleDataparams p1 = new RuleDataparams();
	    		p1.setDatasetId(grouopSet.getId());
	    		p1.setProjectcode(projectCode);
	    		p1.setChzn("规则分数");
	    		p1.setName("ruleScoreList");
	    		p1.setCollection("List");
	    		p1.setIsCollections("true");
	    		p1.setIsDerives("false");
	    		p1.setIsout("false");
	    		p1.setType("Double");
	    		p1.setDefaultValue("0");
	    		p1.setCreateBy(user);
	    		pList.add(p1);
    		}
    		if(!isExistParam(projectCode,grouopSet.getId(),"ruleScoreSum")) {
	    		RuleDataparams p2 = new RuleDataparams();
	    		p2.setDatasetId(grouopSet.getId());
	    		p2.setProjectcode(projectCode);
	    		p2.setChzn("规则总分");
	    		p2.setName("ruleScoreSum");
	    		p2.setCollection("");
	    		p2.setIsCollections("false");
	    		p2.setIsDerives("false");
	    		p2.setIsout("false");
	    		p2.setDomain("[0,9999999]");
	    		p2.setType("Double");
	    		p2.setDefaultValue("0");
	    		p2.setCreateBy(user);
	    		pList.add(p2);
    		}
    		if(!isExistParam(projectCode,grouopSet.getId(),"activeList")) {
	    		RuleDataparams p3 = new RuleDataparams();
	    		p3.setDatasetId(grouopSet.getId());
	    		p3.setProjectcode(projectCode);
	    		p3.setChzn("触发规则列表");
	    		p3.setName("activeList");
	    		p3.setCollection("List");
	    		p3.setIsCollections("true");
	    		p3.setIsDerives("false");
	    		p3.setIsout("false");
	    		p3.setType("String");
	    		p3.setCreateBy(user);
	    		pList.add(p3);
    		}
    		if(!isExistParam(projectCode,grouopSet.getId(),"activeEntryList")) {
	    		RuleDataparams p4 = new RuleDataparams();
	    		p4.setDatasetId(grouopSet.getId());
	    		p4.setProjectcode(projectCode);
	    		p4.setChzn("触发条目列表");
	    		p4.setName("activeEntryList");
	    		p4.setCollection("List");
	    		p4.setIsCollections("true");
	    		p4.setIsDerives("false");
	    		p4.setIsout("false");
	    		p4.setType("String");
	    		p4.setCreateBy(user);
	    		pList.add(p4);
    		}

    		if( !isExistParam(projectCode,grouopSet.getId(),"activegroupList") ) {
        		RuleDataparams p5 = new RuleDataparams();
        		p5.setDatasetId(dsList.get(0).getId());
        		p5.setProjectcode(projectCode);
        		p5.setChzn("包含规则集列表");
        		p5.setName("activegroupList");
        		p5.setCollection("List");
        		p5.setIsCollections("true");
        		p5.setType("String");
        		p5.setIsDerives("false");
        		p5.setIsout("false");
        		p5.setCreateBy(user);
        		pList.add(p5);
    		}
    		ruleDataparamsService.insertBatch(pList);
    	}
    	
    	//一个决策树生成一个分类结果变量，该变量都属于分类结果集这个数据集
    	if(RuleModelTypeEnum.DecisionTree.code.equals(type)) {
    		String chzn = name+"_分类结果";

    		RuleDataparams cfyResult = new RuleDataparams();
    		cfyResult.setProjectcode(projectCode);
    		cfyResult.setName(code);
    		cfyResult.setDatasetId(dsList.get(0).getId());
    		cfyResult.setName(code);
    		cfyResult.setIsCollections("false");
    		cfyResult.setIsDerives("false");
    		cfyResult.setIsout("false");
    		cfyResult.setType("String");
    		List<RuleDataparams> dstList = ruleDataparamsService.findList(cfyResult);
    		if(dstList.size()==0) {//新增保存
    			cfyResult.setChzn(chzn);
    			cfyResult.setCreateBy(user);
        		ruleDataparamsService.save(cfyResult);
    		}else {//更新
	    		RuleDataparams dst1 = dstList.get(0);
	    		if( !chzn.equals(dstList.get(0).getChzn()) ) {
	    			dst1.setChzn(chzn);
	    			ruleDataparamsService.save(dst1);
	    		}
    		}  
    	}
    	if(RuleModelTypeEnum.ScoreModel.code.equals(type)) { 
    		String chzn = name+"_模型名称";
    		
    		RuleDataparams cfyResult = new RuleDataparams();
    		cfyResult.setProjectcode(projectCode);
    		cfyResult.setName(code);
    		cfyResult.setDatasetId(dsList.get(0).getId()); 
    		cfyResult.setName(code);
    		cfyResult.setIsCollections("false");
    		cfyResult.setIsDerives("false");
    		cfyResult.setIsout("false");
    		cfyResult.setType("String");
    		cfyResult.setCreateBy(user);
    		List<RuleDataparams> dstList = ruleDataparamsService.findList(cfyResult);
    		if(dstList.size()==0) {//新增保存
    			cfyResult.setChzn(chzn);
        		ruleDataparamsService.save(cfyResult);
    		}else {//更新
	    		RuleDataparams dst1 = dstList.get(0);
	    		if( !chzn.equals(dst1.getChzn()) ) {
	    			dst1.setChzn(chzn);
	    			ruleDataparamsService.save(dst1);
	    		}
    		}
    	}
    	if (RuleModelTypeEnum.ExecutionBlock.code.equals(type)) {
    		RuleDataset grouopSet = new RuleDataset();
			grouopSet.setProjectcode(projectCode);
			grouopSet.setName(code);
			grouopSet.setParamType("ALL");
			grouopSet.setIsbuiltin("1");
			List<RuleDataset> dstList = this.findList(grouopSet);
			if( dstList.size()==0 ) {
				grouopSet.setChzn(name);
				grouopSet.setCreateBy(user);
				this.save(grouopSet);
			}else {
				RuleDataset dst1 = dstList.get(0);
	    		if( !name.equals(dstList.get(0).getChzn()) ) {
	    			dst1.setChzn(name);
	    			this.save(dst1);
	    		}
			}
    		List<RuleDataparams> pList = new ArrayList<RuleDataparams>();
    		
    		if(!isExistParam(projectCode,grouopSet.getId(),"pakWeigh")) {
	    		RuleDataparams p1 = new RuleDataparams();
	    		p1.setDatasetId(grouopSet.getId());
	    		p1.setProjectcode(projectCode);
	    		p1.setChzn("规则权重总分");
	    		p1.setName("pakWeigh");
	    		p1.setCollection("");
	    		p1.setIsCollections("false");
	    		p1.setIsDerives("false");
	    		p1.setIsout("false");
	    		p1.setDomain("[0,9999999]");
	    		p1.setType("Double");
	    		p1.setDefaultValue("0");
	    		p1.setCreateBy(user);
	    		pList.add(p1);
    		}
    		

    		if(!isExistParam(projectCode,grouopSet.getId(),"pakList")) {
	    		RuleDataparams p3 = new RuleDataparams();
	    		p3.setDatasetId(grouopSet.getId());
	    		p3.setProjectcode(projectCode);
	    		p3.setChzn("去重规则列表");
	    		p3.setName("pakList");
	    		p3.setCollection("List");
	    		p3.setIsCollections("true");
	    		p3.setIsDerives("false");
	    		p3.setIsout("false");
	    		p3.setType("String");
	    		p3.setCreateBy(user);
	    		pList.add(p3);
    		}
    		
    		if(!isExistParam(projectCode,grouopSet.getId(),"pakgroupList")) {
        		RuleDataparams p4 = new RuleDataparams();
        		p4.setDatasetId(grouopSet.getId());
        		p4.setProjectcode(projectCode);
        		p4.setChzn("包含规则集列表");
        		p4.setName("pakgroupList");
        		p4.setCollection("List");
        		p4.setIsCollections("true");
        		p4.setType("String");
        		p4.setIsDerives("false");
        		p4.setIsout("false");
        		p4.setCreateBy(user);
        		pList.add(p4);
    		}
    		ruleDataparamsService.insertBatch(pList);
    		
    	}
    }
    private boolean isExistParam(String projectCode,String datasetId,String name) {
		RuleDataparams cfyResult = new RuleDataparams();
		cfyResult.setProjectcode(projectCode);
		cfyResult.setName(name);
		cfyResult.setDatasetId(datasetId);
		List<RuleDataparams> dstList = ruleDataparamsService.findList(cfyResult);
		if(dstList.size()==0)
			return false;
		return true;
    }

    /**
     * 添加条目的优先级,权重
     * @param code
     * @param entryCode
     * @param entryname
     * @param projectCode
     */
    public void saveOrUpdateEntryBuitineParam(String code,String entryCode,String name,String entryname,String projectCode) {
    	DataCache.paramChange(projectCode);
		RuleDataset grouopSet = new RuleDataset();
		grouopSet.setProjectcode(projectCode);
		grouopSet.setName(code);
		grouopSet.setParamType("ALL");
		grouopSet.setIsbuiltin("1");
		List<RuleDataset> dsList = this.findList(grouopSet);
		if( dsList.size()>0 ) {
			grouopSet = dsList.get(0);
			if( !name.equals(grouopSet.getChzn()) ) {//更新
				grouopSet.setChzn(name);
				this.save(grouopSet);
			}
		}else {//新增保存
			grouopSet.setChzn(name);
			this.save(grouopSet);
		}
		
		RuleDataparams conn = new RuleDataparams();
		conn.setDatasetId(grouopSet.getId());
		conn.setProjectcode(projectCode);
		conn.setIsCollections("false");
		conn.setIsDerives("false");
		conn.setIsout("false");
		List<RuleDataparams> pList = ruleDataparamsService.findList(conn);
		if(pList.size()>0) {
			for(RuleDataparams rpd:pList) {
				if( !(entryname+"临时优先级").equals(rpd.getChzn()) && (entryCode+"_priority").equals(rpd.getName()) ) {
					rpd.setChzn(entryname+"临时优先级");
					ruleDataparamsService.save(rpd);
				}
				if( !(entryname+"条目总权重").equals(rpd.getChzn()) && (entryCode+"_totalweight").equals(rpd.getName()) ) {
					rpd.setChzn(entryname+"条目总权重");
					ruleDataparamsService.save(rpd);
				}
			}
		}else {
			conn.setChzn(entryname+"临时优先级");
			conn.setName(entryCode+"_priority");
			conn.setType("Long");
			conn.setDefaultValue("99999");
			pList.add(conn);
			
			RuleDataparams p2 = new RuleDataparams();
			p2.setDatasetId(grouopSet.getId());
			p2.setProjectcode(projectCode);
			p2.setChzn(entryname+"条目总权重");
			p2.setName(entryCode+"_totalweight");
			p2.setIsCollections("false");
			p2.setIsDerives("false");
			p2.setIsout("false");
			p2.setDomain("[0,9999999]");
			p2.setType("Double");
			p2.setDefaultValue("0");
			pList.add(p2);
			
			ruleDataparamsService.insertBatch(pList);
		}

    }
    
    /**
     * 删除条目的优先级，权重
     * @param code
     * @param entryCode
     * @param entryname
     * @param projectCode
     */
    public void deleteEntryBuitineParam(String code,String entryCode,String name,String entryname,String projectCode) {
    	DataCache.paramChange(projectCode);
		RuleDataset grouopSet = new RuleDataset();
		grouopSet.setProjectcode(projectCode);
		grouopSet.setName(code);
		grouopSet.setChzn(name);
		grouopSet.setParamType("ALL");
		grouopSet.setIsbuiltin("1");
		List<RuleDataset> dsList = this.findList(grouopSet);
		if(dsList!=null && dsList.size()>0) {
			grouopSet = dsList.get(0);
			RuleDataparams p1 = new RuleDataparams();
			p1.setDatasetId(grouopSet.getId());
			p1.setProjectcode(projectCode);
			p1.setChzn(entryname+"临时优先级");
			p1.setName(entryCode+"_priority");
			p1.setIsCollections("false");
			p1.setIsDerives("false");
			p1.setIsout("false");
			p1.setType("Long");
			p1.setDefaultValue("99999");
			List<RuleDataparams> p1list = ruleDataparamsService.findList(p1);
			if(p1list.size()>0) {
				p1 = p1list.get(0);
				ruleDataparamsService.delete(p1);	
			}
			RuleDataparams p2 = new RuleDataparams();
			p2.setDatasetId(grouopSet.getId());
			p2.setProjectcode(projectCode);
			p2.setChzn(entryname+"条目总权重");
			p2.setName(entryCode+"_totalweight");
			p2.setIsCollections("false");
			p2.setIsDerives("false");
			p2.setIsout("false");
			p2.setDomain("[0,9999999]");
			p2.setType("Double");
			p2.setDefaultValue("0");
			List<RuleDataparams> p2list = ruleDataparamsService.findList(p2);
			if(p2list.size()>0) {
				p2 = p2list.get(0);
				ruleDataparamsService.delete(p2);
			}
		}
    }
    /**
     * 更新内置变量
     */
    public void updateBuiltinParam(String code,String name,String type,String projectCode) {
    	if(StringUtils.isNotEmpty(name)) {
        	DataCache.paramChange(projectCode);
    		if(RuleModelTypeEnum.PolicyRuleGroup.code.equals(type)||RuleModelTypeEnum.ExecutionBlock.code.equals(type)) {
    			RuleDataset grouopSet = new RuleDataset();
    			grouopSet.setProjectcode(projectCode);
    			grouopSet.setName(code);
    			
    			grouopSet.setParamType("ALL");
    			grouopSet.setIsbuiltin("1");
    			List<RuleDataset> grouopSets = this.findList(grouopSet);
    			if(grouopSets!=null && grouopSets.size() > 0) {
    				grouopSet = grouopSets.get(0);
    				grouopSet.setChzn(name);
    				this.save(grouopSet);
    			}
    		}else if(RuleModelTypeEnum.DecisionTree.equals(type)) {
    	    	RuleDataparams cfyResult = new RuleDataparams();
    	    	cfyResult.setProjectcode(projectCode);
    	    	cfyResult.setIsCollections("false");
    	    	cfyResult.setIsDerives("false");
    	    	cfyResult.setIsout("false");
    	    	cfyResult.setName(code);
    	    	cfyResult.setType("String");
    	    	List<RuleDataparams> dstList = ruleDataparamsService.findList(cfyResult);
    	    	if(dstList.size()>0) {
    	    		RuleDataparams dst1 = dstList.get(0);
    	        	dst1.setChzn(name+"_分类结果");
    	        	ruleDataparamsService.save(dst1);
    	    	}    
    	    }else if(RuleModelTypeEnum.ScoreModel.equals(type)) { 
	    		RuleDataparams cfyResult = new RuleDataparams();
	    		cfyResult.setProjectcode(projectCode);
	    		cfyResult.setName(code);
	    		cfyResult.setIsCollections("false");
	    		cfyResult.setIsDerives("false");
	    		cfyResult.setIsout("false");
	    		cfyResult.setType("String");
	    		List<RuleDataparams> dstList = ruleDataparamsService.findList(cfyResult);
	    		if(dstList.size()>0) {
	    			RuleDataparams dst1 = dstList.get(0);
	        		dst1.setChzn(name+"_模型名称");
	        		ruleDataparamsService.save(dst1);
	    		}   
    	    }

    	}
    }
    /**
     * 内置变量清理
     * @param code
     * @param name
     * @param type
     * @param projectCode
     */
    public void deleteBuiltinParam(String code,String name,String type,String projectCode) {
    	DataCache.paramChange(projectCode);
		if(RuleModelTypeEnum.PolicyRuleGroup.code.equals(type)||RuleModelTypeEnum.ExecutionBlock.code.equals(type)) {
			RuleDataset grouopSet = new RuleDataset();
			grouopSet.setProjectcode(projectCode);
			grouopSet.setName(code);
			grouopSet.setChzn(name);
			grouopSet.setParamType("ALL");
			grouopSet.setIsbuiltin("1");
			List<RuleDataset> grouopSets = this.findList(grouopSet);
			if(grouopSets!=null && grouopSets.size() > 0) {
				for(RuleDataset rs: grouopSets) {
					this.delete(rs);
					RuleDataparams findRDP = new RuleDataparams();
					findRDP.setDatasetId(rs.getId());
					findRDP.setProjectcode(projectCode);
					List<RuleDataparams> rdps = ruleDataparamsService.findList(findRDP);
					for(RuleDataparams rdp:rdps) {
						ruleDataparamsService.delete(rdp);
					}
				}
			}
		}else if(RuleModelTypeEnum.DecisionTree.code.equals(type)) {
	    	RuleDataparams cfyResult = new RuleDataparams();
	    	cfyResult.setProjectcode(projectCode);
	    	cfyResult.setIsCollections("false");
	    	cfyResult.setIsDerives("false");
	    	cfyResult.setIsout("false");
	    	cfyResult.setName(code);
	    	cfyResult.setChzn(name+"_分类结果");
	    	cfyResult.setType("String");
	    	List<RuleDataparams> dstList = ruleDataparamsService.findList(cfyResult);
	    	if(dstList.size()>0) {
	    		for(RuleDataparams dst:dstList) {
	    			ruleDataparamsService.delete(dst);
	    		}
	    	}
	    }else if(RuleModelTypeEnum.ScoreModel.equals(type)) { 
    		RuleDataparams cfyResult = new RuleDataparams();
    		cfyResult.setProjectcode(projectCode);
    		cfyResult.setName(code);
    		cfyResult.setIsCollections("false");
    		cfyResult.setIsDerives("false");
    		cfyResult.setChzn(name+"_模型名称");
    		cfyResult.setIsout("false");
    		cfyResult.setType("String");
	    	List<RuleDataparams> dstList = ruleDataparamsService.findList(cfyResult);
	    	if(dstList.size()>0) {
	    		for(RuleDataparams dst:dstList) {
	    			ruleDataparamsService.delete(dst);
	    		}
	    	}
	    }
    }
    @Override
	public void firstDefinition(RuleDatamodel dm) {
		//删除名为FirstDefaultModel的数据模型
		RuleDatamodelDao.deleteDefault(dm);
		//新建初始化数据模型
		RuleDatamodelDao.buildFirstDefinition(dm);
		//关联id
        RuleDatamodelDao.buildDataset(dm);
	}
	/**
     *  鏇存柊鏁版嵁闆嗗叧鑱攊d
     */
    public void updateDMRank(RuleDataset dataset) {
    	this.dao.updateDMRank(dataset);
    }


	
    
    /**
     * 更新关联层级ID（初始化）
     * @param condition
     * @return
     */
    public int updateRankId(RuleDatamodel condition) {
    	return RuleDatamodelDao.updateRankId(condition);
    }
    
    /**
     * 根据条件获取数据量
     * @param condition
     * @return
     */
    public int countList(RuleDataset condition) {
    	return this.dao.countList(condition);
    }
	@Override
	public void deleteflag(RuleDataset ruleDataset) {
		this.dao.deleteflag(ruleDataset);
		
	}
	public void moveUpset(RuleDataset dm) {
		RuleDatasetDao.moveUpdate(dm);
		
	}
	
	public void moveUpFunc(RuleDataparams condition) {
		ruleDataparamsDao.moveUpFunc(condition);
		
	}
	
	/**
	 * 数据模型移动判断
	 * @param ids
	 * @param ranklistForSelfManage
	 * @param ranklist
	 * @param nodeId
	 * @param moveType
	 */

	public ResMessage moveModelCheck(String id, List<RuleDataset> ranklistForSelfData, List<RuleProjectRank> ranklist, String nodeId,
			String moveType) {
		 ResMessage msg = null;
		 String RankRelationId = "";
		 for (RuleProjectRank dataset : ranklist) {
           	if(nodeId.equals(dataset.getNodeId())) {
           		RankRelationId =  dataset.getTid();//获取目的地组件的RankRelationId。
           	}
         }
         if(!"".equals(RankRelationId)) {//非空判断
        	 if(ranklistForSelfData.size()>0) {
        		 if(ranklistForSelfData.get(0).getRankRelationId().equals(RankRelationId)) {
        			 msg= new ResMessage("failure", "请选择非原路径进行移动。");
        		 }else{//移动
        			 RuleDataset dm = new RuleDataset();
        			 dm.setId(id);
             		 dm.setRankRelationId(RankRelationId);
             		 this.moveUpset(dm);	
             		 msg =new ResMessage("success", "移动成功");
        		 }
        	 }
         }else {
			 msg= new ResMessage("failure", "未选中要移动的目的组件，前在弹出框中重新选择！");
		 } 
		return msg;
		
	}
	
	/**
	 * 函数变量移动判断
	 * @param ids
	 * @param ranklistForSelfFunc
	 * @param ranklist
	 * @param nodeId
	 * @param moveType
	 */
	public ResMessage moveFuncCheck(String id, List<RuleDataparams> ranklistForSelfFunc, List<RuleProjectRank> ranklist, String nodeId,
			String moveType) {
		ResMessage msg = null;
		 String RankRelationId = "";
		 for (RuleProjectRank dataset : ranklist) {
          	if(nodeId.equals(dataset.getNodeId())) {
          		RankRelationId =  dataset.getTid();//获取目的地组件的RankRelationId。
          	}
        }
		 if(!"".equals(RankRelationId)) {//非空判断
			 if(ranklistForSelfFunc.size()>0) {
	    		 if(ranklistForSelfFunc.get(0).getRankRelationId().equals(RankRelationId)) {
	    			 msg= new ResMessage("failure", "请选择非原路径进行移动。");
	    		 }else{
	    			 RuleDataparams condition = new RuleDataparams();
	         		 condition.setRankRelationId(RankRelationId);
	         		 condition.setId(id);
	         		 this.moveUpFunc(condition);
	         		msg =new ResMessage("success", "移动成功");
	    		 }
	    	 }
		 }else {
			 msg= new ResMessage("failure", "未选中要移动的目的组件，前在弹出框中重新选择！");
		 }
		 
		 return msg;
	}
	
	
	/**
	 * 规则组件移动判断
	 * @param ids
	 * @param ranklistForSelfManage
	 * @param ranklist
	 * @param nodeId
	 * @param moveType
	 */
	public ResMessage moveManageCheck(String id, List<RuleManage> ranklistForSelfManage, List<RuleProjectRank> ranklist, String nodeId,
			String moveType) {
		ResMessage msg = null;
		 String RankRelationId = "";
		 for (RuleProjectRank dataset : ranklist) {
          	if(nodeId.equals(dataset.getNodeId())) {
          		RankRelationId =  dataset.getTid();//获取目的地组件的RankRelationId。
          	}
        }
		 if(!"".equals(RankRelationId)) {//非空判断
			 if(ranklistForSelfManage.size()>0) {
	    		 if(ranklistForSelfManage.get(0).getRankRelationId().equals(RankRelationId)) {
	    			 msg= new ResMessage("failure", "请选择非原路径进行移动。");
	    		 }else{
	    			 RuleManage condition = new RuleManage();
	         		 condition.setRankRelationId(RankRelationId);
	         		 condition.setId(id);
	         		 ruleManageService.updateRankId(condition);
	         		msg =new ResMessage("success", "移动成功");
	    		 }
	    	 }
		 }else {
			 msg= new ResMessage("failure", "未选中要移动的目的组件，前在弹出框中重新选择！");
		 }
		 
		 return msg;
	}

	
	/**
	 * 移动
	 * @param ids
	 * @param rankRelationId
	 * @param moveType
	 */
	public ResMessage move(String id,String projectCode,String nodeId,String moveType) {
		ResMessage msg = null;
		RuleProjectRank rankCondition = new RuleProjectRank();
        rankCondition.setProjectCode(projectCode);
        rankCondition.setModuleType(moveType);
        List<RuleProjectRank> ranklist = ruleProjectRankService.findList(rankCondition);//获取所有当前移到记录同类型的组件信息
//		String[] param = ids.split(",");
//    	for (String id : param) {
    		 List<RuleDataset> ranklistForSelfData = new ArrayList<RuleDataset>();
    		 List<RuleManage> ranklistForSelfManage = new ArrayList<RuleManage>();
    		 List<RuleDataparams> ranklistForSelfFunc = new ArrayList<RuleDataparams>();
    		if("datamodel".equalsIgnoreCase(moveType)) {
    			RuleDataset ruleDataset = new RuleDataset();
    	        ruleDataset.setProjectcode(projectCode);
    	        ruleDataset.setId(id);
    	        ranklistForSelfData = RuleDatasetDao.findList(ruleDataset);//获取当前需移动的数据模型记录的具体信息
    	        //数据模型移动情况判断
    			msg = this.moveModelCheck(id, ranklistForSelfData, ranklist, nodeId, moveType);	
    		}else {
    			if("funcparam".equals(moveType)) {
    				RuleDataparams ruleDataParams = new RuleDataparams();
    				ruleDataParams.setProjectcode(projectCode);
    				ruleDataParams.setIsfuncparam("1");
    				ruleDataParams.setId(id);
    				ranklistForSelfFunc = ruleDataparamsService.findList(ruleDataParams);
    				 //函数变量移动情况判断
        			msg = this.moveFuncCheck(id,ranklistForSelfFunc,ranklist, nodeId, moveType);
    			}else {
    				RuleManage ruleManage = new RuleManage();
        			ruleManage.setProjectCode(projectCode);
        			ruleManage.setId(id);
        			ranklistForSelfManage = ruleManageDao.findList(ruleManage);//获取当前需移动的规则组件记录的具体信息
        			//规则组件移动情况判断
        			msg = this.moveManageCheck(id,ranklistForSelfManage,ranklist, nodeId, moveType);
    			}
    			
        		
//    		}
        }
		return msg;
	
	}

	@Override
	public void updateModelType(String projectCode) {
    	RuleDataparams ruleDataparams = new RuleDataparams();
		ruleDataparams.setProjectcode(projectCode);
		ruleDataparams.setIsfuncparam("1");
		List<RuleDataparams> rds = this.ruleDataparamsDao.findList(ruleDataparams);
		if(rds!=null && rds.size()>0){
			for(RuleDataparams rd : rds){
				String datasetId = rd.getDatasetId();
				RuleDataset ruleDataset = this.RuleDatasetDao.get(datasetId);
				ruleDataset.setParamType("funcparam");
				this.RuleDatasetDao.update(ruleDataset);
			}
		}
	}

	@Override
	public void deleteDataSetByIds(List<String> ids) throws Exception {
		// TODO Auto-generated method stub
		if(ids != null && ids.size() > 0) {
			Map<String,Object> map =  new HashMap<>();
			map.put("ids", ids);
			RuleDatasetDao.deleteDataSetByIds(map);
		}
	}

	@Override
	public void saveAndUpdateRef(RuleDataset ruleDataset) throws  Exception {
        RuleDataset  preRuleDataset = this.dao.get(ruleDataset.getId());
        if (preRuleDataset != null) {
        	if (!preRuleDataset.getName().equals(ruleDataset.getName())) {
        		RuleSetParamInfo  oldParamInfo = new  RuleSetParamInfo();
        		oldParamInfo.setCode(preRuleDataset.getName());
        		oldParamInfo.setName(preRuleDataset.getChzn());
        		RuleSetParamInfo  newParamInfo = new  RuleSetParamInfo();
        		newParamInfo.setCode(ruleDataset.getName());
        		newParamInfo.setName(ruleDataset.getChzn());
        		this.ruleSetParmOperator.upateRuleModel(ruleDataset.getProjectcode(), newParamInfo, oldParamInfo, true); 
        		ruleDataset.setIsNewRecord(false);
                
        		this.save(ruleDataset);
                
        	}
        }
		
	}

    
//     public   void  pakGroup(String  projectCode,String gropCode,String  code) {
// 		 RuleDataset grouopSet = new RuleDataset();
//		 grouopSet.setProjectcode(projectCode);
//		 grouopSet.setName(gropCode);
//		 grouopSet.setParamType("ALL");
//		 grouopSet.setIsbuiltin("1");
//		 List<RuleDataset> dList = this.dao.findList(grouopSet);
//		 if (dList != null  &&  dList.size() >0) {
//     		RuleDataparams p4 = new RuleDataparams();
//     		p4.setDatasetId(dList.get(0).getId());
//     		p4.setProjectcode(projectCode);
//     		List<RuleDataparams>  pList =this.ruleDataparamsDao.findList(p4);
//     		for  (RuleDataparams dp: pList) {
//     			if (dp.getName() !=null && dp.getName().equals("") ) {
//     				
//     			}
//     		}
//		 }
//		
//    	 
//     }

}